package com.ruiyi.adrobot.web.controller;

import com.ruiyi.adrobot.Token;
import com.ruiyi.adrobot.domain.common.MongoPageRequest;
import com.ruiyi.adrobot.domain.common.ResultMsg;
import com.ruiyi.adrobot.domain.company.Company;
import com.ruiyi.adrobot.mongo.company.CompanyRepository;
import com.ruiyi.adrobot.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * Created by tao.zeng on 2017/8/2.
 */
@Controller
@RequestMapping("/company")
public class CompanyController {
    @Autowired
    private CompanyRepository companyRepository;


    @GetMapping("/toList")
    public String toList() {
        return "company/list";
    }

    @GetMapping("/getListByPage")
    @ResponseBody
    public Page<Company> getListByPage(MongoPageRequest<Map<String, Object>> mongoPageRequest) {
        return companyRepository.getListByPage(mongoPageRequest);
    }

    @GetMapping("/toAdd")
    public String toAdd() {
        return "company/add";
    }


    @GetMapping("/addFun")
    @ResponseBody
    public ResultMsg addFun(String id, Integer fun) {
        Company company = companyRepository.findOne(id);
        company.getFuns().add(fun);
        companyRepository.save(company);
        return ResultMsg.success();
    }

    @PostMapping("/add")
    @ResponseBody
    public ResultMsg add(Company company) {
        try {
            if (companyRepository.findByUserName(company.getUserName()) == null) {
                company.setCreateTime(DateUtil.getCurrentTime());
                companyRepository.insert(company);
            } else {
                return ResultMsg.error(3, "用户名已存在");
            }
        } catch (Exception e) {
            return ResultMsg.error();
        }
        return ResultMsg.success();
    }

    @GetMapping("/token")
    @ResponseBody
    public ResultMsg<Token> getToken(String userName, String appId) {
        ResultMsg<Token> resultMsg = new ResultMsg<>();
        String uuid = UUID.randomUUID().toString();
        Company company = companyRepository.findByIdAndUserName(appId, userName);
        if (null != company) {
            company.setAccessToken(uuid);
            company.setDeadline(new Date().getTime() + 86400000);
            companyRepository.save(company);
            resultMsg.setReturnInfo(new Token(uuid, company.getDeadline()));
            return resultMsg;
        } else {
            return resultMsg.error(1, "用户名和appid不匹配");
        }
    }
}
